package com.sugar;


public class oddEvenList_zijie {
    static class ListNode{
        int val;
        ListNode next;

        ListNode(int val){
            this.val = val;
        }

        ListNode(int val,ListNode next){
            this.next = next;
            this.val = val;
        }
    }

    public ListNode solution(ListNode head){
        if(head==null || head.next == null) return new ListNode(0);
        ListNode odd = head;
        ListNode even = head.next;
        ListNode evenhead = even;

        while(even!=null && even.next!=null){
            odd.next = even.next;
            odd = odd.next;
            even.next = odd.next;
            even = even.next;
        }

        odd.next = null;
        even.next = null;

        ListNode revEven = reverse(evenhead);

        ListNode merged = merge(head,revEven);

        return merged;
    }

    public ListNode reverse(ListNode head){
        ListNode pre = null;
        ListNode cur = head;
        while (cur!=null){
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }

    public ListNode merge(ListNode l1,ListNode l2){
        ListNode dummy = new ListNode(-1);
        ListNode cur = dummy;
        while (l1!=null && l2!=null){
            if(l1.val<= l2.val){
                cur.next = l1;
                l1 = l1.next;
            }else{
                cur.next = l2;
                l2 = l2.next;
            }
            cur = cur.next;
        }
        while(l1!=null) {
            cur.next = l1;
            l1 = l1.next;
            cur = cur.next;
        }
        while(l2!=null) {
            cur.next = l2;
            l2 = l2.next;
            cur = cur.next;
        }
        return dummy.next;
    }

    public void printListNode(ListNode head){
        ListNode cur = head;
        while (cur!=null){
            System.out.println(cur.val);
            cur = cur.next;
        }
    }

    public static void main(String[] args){
        ListNode head = new ListNode(1);
        head.next = new ListNode(6);
        head.next.next = new ListNode(2);
        head.next.next.next = new ListNode(5);
        head.next.next.next.next = new ListNode(3);
        head.next.next.next.next.next = new ListNode(4);

        oddEvenList_zijie sol = new oddEvenList_zijie();
        sol.printListNode(sol.solution(head));
    }

}
